package com.Travit;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.google.zxing.integration.android.IntentIntegrator;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.TextView;

public class Retail extends Activity{

	String loggedid;
	String loggedname;
	ImageButton recieveProduct;
	ImageButton sold;
	ImageButton logout;
	String barcodeid;
	TextView top;
	
	private static final int DIALOG_YES_NO_MESSAGE = 1;
	
	private boolean scanned=false;
	private static String shippingOrRecieving="none";
	private static String urlRequestValidateBoxBarcode = "http://project492.engr.sjsu.edu/travITvalidateBox.php";
	private static String scannedItem="";
	private static String urlValidateProductBarcode="http://project492.engr.sjsu.edu/travITupdatebarcode.php";
	public void onCreate(Bundle savedInstanceState){
		Log.v("in", "retails");
		super.onCreate(savedInstanceState);
		Log.i("login", "time");
		Bundle extras = getIntent().getExtras();
		setContentView(R.layout.retailhome);
		setTitle(R.string.retailtitle);
		loggedid = extras.getString("loggedid");
		loggedname = extras.getString("loggedinuser");
		Log.v("name should be", ""+loggedname);
		top = (TextView) findViewById(R.id.textView2);
		top.setText("Welcome " + loggedname + "!");
		recieveProduct = (ImageButton) findViewById(R.id.retailRecieveProduct);
		sold = (ImageButton) findViewById(R.id.soldbutton);
		logout = (ImageButton) findViewById(R.id.logout);

		logout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//SHOW INFORMATION FROM BARCODE
				//initialize barcodeid
				Intent newIntent = new Intent(v.getContext(), TravITActivity.class);
				//newIntent.putExtra("venid", loggedid);
				Log.i("logout", "retail");
		        startActivity(newIntent);
			}			
		});

		recieveProduct.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent("com.google.zxing.client.android.SCAN");
		        intent.setPackage("com.google.zxing.client.android");
		        intent.putExtra("com.google.zxing.client.android.SCAN.SCAN_MODE", "QR_CODE_MODE");
		        shippingOrRecieving="shipping";
		        startActivityForResult(intent, 0);
			
			}
		});
		
		sold.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//SHOW INFORMATION FROM BARCODE
//				onCreateDialog(DIALOG_YES_NO_MESSAGE);
				/*
				AlertDialog.Builder builder = new AlertDialog.Builder(
						Retail.this);
				builder.setMessage("Invalid Product");
				builder.setCancelable(false);
				builder.setNeutralButton("Okay", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						
					}
				});
				builder.show();
			*/
				scanned = true;
				Log.v("starting", "barcode");
				Intent intent = new Intent("com.google.zxing.client.android.SCAN");
		        intent.setPackage("com.google.zxing.client.android");
			    intent.putExtra("com.google.zxing.client.android.SCAN.SCAN_MODE", "QR_CODE_MODE");
			    startActivityForResult(intent, 0);
				
			    
//				Log.v("inside", "soldbuttonclicked");
//				Log.v("going back", "from outside ifelse");
//				Intent newIntent = new Intent(v.getContext(), Retail.class);
//				newIntent.putExtra("venid", loggedid);
//				startActivity(newIntent);

			}			
		});
	}
	
	protected Dialog onCreateDialog(int id)
	{
		switch(id){
		case DIALOG_YES_NO_MESSAGE:
			return new AlertDialog.Builder(Retail.this)
			.setPositiveButton("OK", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					Log.v("clicked", "yes");
				}
			})
			.setNegativeButton("CA", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					
				}
			}).create();
			
		}
		return null;
	}
	
	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
		
	    if (requestCode == 0) {
	        if (resultCode == RESULT_OK) {
	            String contents = intent.getStringExtra("SCAN_RESULT");
	            String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
	            // Handle successful scan
	            Log.v("scanned propoerly", "yes");
	            Log.v("intent",""+intent);
	            Log.v("scanned item is:",contents);
	            TravITActivity t=new TravITActivity();
	            String[]temp=contents.split("/-");
	            for(int i=0;i<temp.length;i++)
	            {
	            	Log.v("i is:"+i, ""+temp[i]);
	            }
	            if(scanned == true)
	            {
					String validinvalid = "n";	//either "y" or "n"
					//barcodeid = "1";
					barcodeid = temp[0];
					HttpClient client = new DefaultHttpClient();
					
					try {
						HttpPost request = new HttpPost(urlValidateProductBarcode
								+ "?makeinvalid=" + validinvalid
								+ "&barcodeID=" + barcodeid);
						Log.v("trying", "before execution");
						List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
						nameValuePairs.add(new BasicNameValuePair("makeinvalid", "n"));
					    nameValuePairs.add(new BasicNameValuePair("barcodeID", barcodeid));
					    request.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			
						HttpResponse response = client.execute(request);
						HttpEntity entity = response.getEntity();
						String responseResult = EntityUtils.toString(entity);
						String[] responseResultArr=responseResult.split(";");
						Log.v("should have sold zero value:", ""+responseResultArr[0]);
						Log.v("should have sold fristvalue:", ""+responseResultArr[0]);
						if(responseResultArr[1].equals("sold"))
						{
							Log.v("now it", "should run");
							//this.createMessage("Invalid Product");
							Log.v("anirudh debugging", "should run");
							AlertDialog.Builder builder = new AlertDialog.Builder(
									Retail.this);
							builder.setMessage("Invalid Product.");
							builder.setCancelable(false);
							builder.setNeutralButton("Okay", new DialogInterface.OnClickListener() {
								
								@Override
								public void onClick(DialogInterface dialog, int which) {
									// TODO Auto-generated method stub
									
								}
							});
							builder.show();
						
						}
						else
						{
							Log.v("executing", "" + responseResult);
							if(responseResult.equalsIgnoreCase("Updated Barcode Validity"))
							{
								AlertDialog.Builder builder = new AlertDialog.Builder(
										Retail.this);
								builder.setMessage("Product with barcode " + contents + " sold successfully.");
								builder.setCancelable(false);
								builder.setNeutralButton("Okay", new DialogInterface.OnClickListener() {
									
									@Override
									public void onClick(DialogInterface dialog, int which) {
										// TODO Auto-generated method stub
										
									}
								});
								builder.show();
								Log.v("in if", "valid product");
								/*Removing so that pop up comes and the user s forced to click enter
								Intent newIntent = new Intent(sold.getContext(), Retail.class);
								newIntent.putExtra("loggedid", loggedid);
								newIntent.putExtra("loggedinuser", loggedname);
								startActivity(newIntent);
								*/
							}
							else
							{
								AlertDialog.Builder builder = new AlertDialog.Builder(
										Retail.this);
								builder.setMessage("Product with barcode " + contents + " sold successfully.");
								builder.setCancelable(false);
								builder.setNeutralButton("Okay", new DialogInterface.OnClickListener() {
									
									@Override
									public void onClick(DialogInterface dialog, int which) {
										// TODO Auto-generated method stub
										
									}
								});
								builder.show();
							
								Log.v("in else", "Updated Barcode Validity");
								/*Removing so that pop up comes and the user s forced to click enter
								Intent newIntent = new Intent(sold.getContext(), Retail.class);
								newIntent.putExtra("loggedid", loggedid);
								newIntent.putExtra("loggedinuser", loggedname);
								startActivity(newIntent);
							*/
							}
						}
					} catch (ClientProtocolException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					}
	            }
	         //   clicker click=t.new clicker();
	            
	            
	           // click.createMessage("contents"+contents);
	            else
	            {
		            HttpGet request = new HttpGet(urlRequestValidateBoxBarcode
		    				+ "?boxbarcodeID="+contents);
		    		HttpClient client = new DefaultHttpClient();
		    		Hashtable<String,String>table;
		    		try{
		    			HttpResponse response=client.execute(request);
		    			HttpEntity entity = response.getEntity();
		    			Log.v("entity:",entity.toString());
		    			String responseResult = EntityUtils.toString(entity);
		    			Log.v("Box Results::",responseResult);
		    			
		    			Log.v("hahahahhahaha","hahahahhaha");
		    			String[] responseResultArr=responseResult.split(";");
		    			responseResultArr[0]=responseResultArr[0].trim();
		    			table=new Hashtable<String,String>();
		    			for(int i=0;i<responseResultArr.length;i+=2){
		    				Log.v("response:",responseResultArr[i]);
		    				int tempVar=i;
		    				tempVar++;
		    				Log.v("result:",responseResultArr[tempVar]);
		    				table.put(responseResultArr[i],responseResultArr[tempVar]);
		    			}
	
		    			if(!table.get("Status").equals("Invalid Box")){
		    		           scanned=true;
		    		           scannedItem=contents;
		    		           Intent newIntent = new Intent(sold.getContext(), RecieveShipment.class);
		    		           newIntent.putExtra("scannedbarcode", contents);
		    		           newIntent.putExtra("Table", responseResultArr);
		    		           newIntent.putExtra("BoxBarCodeID", contents);
		    		           newIntent.putExtra("loggedid", loggedid);
		    		           newIntent.putExtra("loginname", loggedname);
		    		           if(shippingOrRecieving.equals("shipping"))
		    		        	   newIntent.putExtra("status", "recieved");
		    		           else
		    		        	   newIntent.putExtra("status", "recieved");
		    		           newIntent.putExtra("updatedByType", "Retail");
		    		           startActivity(newIntent);
		    		    }
		    			
		    		}
		    		catch (Exception e) {
		    			// TODO Auto-generated catch block
		    			e.printStackTrace();
		    		}
	            }
	    		
	            
	        } else if (resultCode == RESULT_CANCELED) {
	            // Handle cancel
	        }
	    }
	}
	
	public void createMessage(String msg) {
		Log.v("createMessage", msg);
		AlertDialog.Builder builder = new AlertDialog.Builder(
				Retail.this);
		builder.setMessage(msg);
		builder.setCancelable(false);
		builder.setNeutralButton("Okay", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				
			}
		});
		builder.show();
	}

}
